﻿///
/// @file IRGenerator.cpp
/// @brief AST遍历产生线性IR的源文件
/// @author zenglj (zenglj@live.com)
/// @version 1.1
/// @date 2024-11-23
///
/// @copyright Copyright (c) 2024
///
/// @par 修改日志:
/// <table>
/// <tr><th>Date       <th>Version <th>Author  <th>Description
/// <tr><td>2024-09-29 <td>1.0     <td>zenglj  <td>新建
/// <tr><td>2024-11-23 <td>1.1     <td>zenglj  <td>表达式版增强
/// </table>
///
#include <cstdint>
#include <cstdio>
#include <unordered_map>
#include <vector>
#include <iostream>

#include "AST.h"
#include "Common.h"
#include "Function.h"
#include "IRCode.h"
#include "IRGenerator.h"
#include "Module.h"
#include "EntryInstruction.h"
#include "LabelInstruction.h"
#include "ExitInstruction.h"
#include "FuncCallInstruction.h"
#include "BinaryInstruction.h"
#include "MoveInstruction.h"
#include "GotoInstruction.h"
#include "CondGotoInstruction.h"
#include "SingleInstruction.h"
#include "CastInstruction.h"
#include "GetElementPtrInstruction.h"
#include "LoadInstruction.h"
#include "StoreInstruction.h"
#include <ConstFloat.h>
/// @brief 构造函数
/// @param _root AST的根
/// @param _module 符号表
IRGenerator::IRGenerator(ast_node * _root, Module * _module) : root(_root), module(_module)
{
    /* 叶子节点 */
    ast2ir_handlers[ast_operator_type::AST_OP_LEAF_LITERAL_UINT] = &IRGenerator::ir_leaf_node_uint;
    ast2ir_handlers[ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT] = &IRGenerator::ir_leaf_node_float;
    ast2ir_handlers[ast_operator_type::AST_OP_LEAF_VAR_ID] = &IRGenerator::ir_leaf_node_var_id;
    ast2ir_handlers[ast_operator_type::AST_OP_LEAF_TYPE] = &IRGenerator::ir_leaf_node_type;
    // 新增处理函数，处理AST_OP_FUNC_FORMAL_PARAM_TYPE节点
    ast2ir_handlers[ast_operator_type::AST_OP_FUNC_FORMAL_PARAM_TYPE] = &IRGenerator::ir_leaf_node_type;

    /* 表达式运算， 加减乘除取余*/
    ast2ir_handlers[ast_operator_type::AST_OP_SUB] = &IRGenerator::ir_sub;
    ast2ir_handlers[ast_operator_type::AST_OP_ADD] = &IRGenerator::ir_add;
    ast2ir_handlers[ast_operator_type::AST_OP_MUL] = &IRGenerator::ir_mul;
    ast2ir_handlers[ast_operator_type::AST_OP_DIV] = &IRGenerator::ir_div;
    ast2ir_handlers[ast_operator_type::AST_OP_MOD] = &IRGenerator::ir_mod;

    /* 关系运算 */
    ast2ir_handlers[ast_operator_type::AST_OP_LESS_EQUAL] = &IRGenerator::ir_less_equal;
    ast2ir_handlers[ast_operator_type::AST_OP_GREATER_EQUAL] = &IRGenerator::ir_greater_equal;
    ast2ir_handlers[ast_operator_type::AST_OP_LESS] = &IRGenerator::ir_less;
    ast2ir_handlers[ast_operator_type::AST_OP_GREATER] = &IRGenerator::ir_greater;
    ast2ir_handlers[ast_operator_type::AST_OP_EQ] = &IRGenerator::ir_eq;
    ast2ir_handlers[ast_operator_type::AST_OP_NEQ] = &IRGenerator::ir_neq;

    /* 逻辑运算 */
    ast2ir_handlers[ast_operator_type::AST_OP_LAND] = &IRGenerator::ir_land;
    ast2ir_handlers[ast_operator_type::AST_OP_LOR] = &IRGenerator::ir_lor;
    ast2ir_handlers[ast_operator_type::AST_OP_UNARY_NOT] = &IRGenerator::ir_lnot;

    /*正负值运算*/
    ast2ir_handlers[ast_operator_type::AST_OP_UNARY_MINUS] = &IRGenerator::ir_unary_minus;
    ast2ir_handlers[ast_operator_type::AST_OP_UNARY_PLUS] = &IRGenerator::ir_unary_plus;

    /* 语句 */
    ast2ir_handlers[ast_operator_type::AST_OP_ASSIGN] = &IRGenerator::ir_assign;
    ast2ir_handlers[ast_operator_type::AST_OP_RETURN] = &IRGenerator::ir_return;
    ast2ir_handlers[ast_operator_type::AST_OP_IF] = &IRGenerator::ir_if;
    ast2ir_handlers[ast_operator_type::AST_OP_ELSE] = &IRGenerator::ir_else;

    /* 函数调用 */
    ast2ir_handlers[ast_operator_type::AST_OP_FUNC_CALL] = &IRGenerator::ir_function_call;

    /* 函数定义 */
    ast2ir_handlers[ast_operator_type::AST_OP_FUNC_DEF] = &IRGenerator::ir_function_define;
    ast2ir_handlers[ast_operator_type::AST_OP_FUNC_FORMAL_PARAMS] = &IRGenerator::ir_function_formal_params;

    /* 变量定义语句 */
    ast2ir_handlers[ast_operator_type::AST_OP_DECL_STMT] = &IRGenerator::ir_declare_statment;
    ast2ir_handlers[ast_operator_type::AST_OP_VAR_DECL] = &IRGenerator::ir_variable_declare;
    ast2ir_handlers[ast_operator_type::AST_OP_VAR_INIT] = &IRGenerator::ir_init;

    /*常量声明定义语句*/
    ast2ir_handlers[ast_operator_type::AST_OP_CONST_DECL] = &IRGenerator::ir_variable_declare;
    ast2ir_handlers[ast_operator_type::AST_OP_CONST_DEF] = &IRGenerator::ir_init;

    /* 语句块 */
    ast2ir_handlers[ast_operator_type::AST_OP_BLOCK] = &IRGenerator::ir_block;

    /* 编译单元 */
    ast2ir_handlers[ast_operator_type::AST_OP_COMPILE_UNIT] = &IRGenerator::ir_compile_unit;

    /* 常量声明和常量定义 */
    ast2ir_handlers[ast_operator_type::AST_OP_CONST_DECL] = &IRGenerator::ir_const_decl;
    ast2ir_handlers[ast_operator_type::AST_OP_CONST_DEF] = &IRGenerator::ir_const_def;

    /* define 宏定义 */
    ast2ir_handlers[ast_operator_type::AST_OP_DEFINE_DECL] = &IRGenerator::ir_define_decl;
    ast2ir_handlers[ast_operator_type::AST_OP_DEFINE_DEF] = &IRGenerator::ir_define;

    /* while 循环 */
    ast2ir_handlers[ast_operator_type::AST_OP_WHILE] = &IRGenerator::ir_while;
    /* break */
    ast2ir_handlers[ast_operator_type::AST_OP_BREAK] = &IRGenerator::ir_break;
    /* continue */
    ast2ir_handlers[ast_operator_type::AST_OP_CONTINUE] = &IRGenerator::ir_continue;
    /* array */
    ast2ir_handlers[ast_operator_type::AST_OP_ARRAY_DECL] = &IRGenerator::ir_array_decl;
    ast2ir_handlers[ast_operator_type::AST_OP_ARRAY_ACCESS] = &IRGenerator::ir_array_access;
    ast2ir_handlers[ast_operator_type::AST_OP_ARRAY_INIT] = &IRGenerator::ir_array_init;

    // /* 类型转换 */
    ast2ir_handlers[ast_operator_type::AST_OP_CAST] = &IRGenerator::ir_cast;
    // /*指针类型*/
    // ast2ir_handlers[ast_operator_type::AST_OP_POINTER_TYPE] = &IRGenerator::ir_pointer_type;
}

/// @brief 遍历抽象语法树产生线性IR，保存到IRCode中
/// @param root 抽象语法树
/// @param IRCode 线性IR
/// @return true: 成功 false: 失败
bool IRGenerator::run()
{
    ast_node * node;

    // 从根节点进行遍历
    node = ir_visit_ast_node(root);

    return node != nullptr;
}

/// @brief 根据AST的节点运算符查找对应的翻译函数并执行翻译动作
/// @param node AST节点
/// @return 成功返回node节点，否则返回nullptr
ast_node * IRGenerator::ir_visit_ast_node(ast_node * node)
{
    // 空节点
    if (nullptr == node) {
        return nullptr;
    }

    bool result;

    std::unordered_map<ast_operator_type, ast2ir_handler_t>::const_iterator pIter;
    pIter = ast2ir_handlers.find(node->node_type);
    if (pIter == ast2ir_handlers.end()) {
        // 没有找到，则说明当前不支持
        result = (this->ir_default)(node);
    } else {
        result = (this->*(pIter->second))(node);
    }

    if (!result) {
        // 语义解析错误，则出错返回
        node = nullptr;
    }
    return node;
}

/// @brief 未知节点类型的节点处理
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_default(ast_node * node)
{
    // 未知的节点
    printf("Unkown node(%d)\n", (int) node->node_type);
    return false;
}

/// @brief 编译单元AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_compile_unit(ast_node * node)
{
    module->setCurrentFunction(nullptr);

    for (auto son: node->sons) {

        // 遍历编译单元，要么是函数定义，要么是语句
        ast_node * son_node = ir_visit_ast_node(son);
        if (!son_node) {
            // TODO 自行追加语义错误处理
            return false;
        }
    }
    return true;
}

/// @brief 函数定义AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_function_define(ast_node * node)
{
    bool result;
    // 1. 处理返回类型节点
    ast_node * type_node = ir_visit_ast_node(node->sons[0]);
    Type * retType = type_node->type;
    ast_node * name_node = node->sons[1];
    ast_node * param_node = node->sons[2];
    ast_node * block_node = node->sons[3];

    // 2. 收集形参和类型列表
    std::vector<FormalParam *> params;
    for (auto & paramAst: param_node->sons) {
        if (paramAst->sons.size() < 2)
            continue;
        // 处理形参类型节点
        ast_node * tNode = ir_visit_ast_node(paramAst->sons[0]);
        Type * pType = tNode->type;
        std::string pName = paramAst->sons[1]->name;
        params.push_back(new FormalParam(pType, pName));
    }
    std::vector<Type *> paramTypes;
    for (auto * p: params) {
        paramTypes.push_back(p->getType());
    }

    bool builtin = false;

    FunctionType * funcType = new FunctionType(retType, paramTypes);
    Function * newFunc = new Function(name_node->name, funcType, builtin);
    if (name_node->name == "main") {
        // 设置main函数为入口函数
        newFunc->setIsmain(true);
    }
    newFunc->getParams() = params;

    // 检查重名
    if (module->findFunction(name_node->name)) {
        delete newFunc;
        return false;
    }
    module->insertFunctionDirectly(newFunc);

    // 当前函数设置有效，变更为当前的函数
    module->setCurrentFunction(newFunc);

    // 进入函数的作用域
    module->enterScope();

    // 获取函数的IR代码列表，用于后面追加指令用，注意这里用的是引用传值
    InterCode & irCode = newFunc->getInterCode();

    // 这里也可增加一个函数入口Label指令，便于后续基本块划分

    // 创建并加入Entry入口指令
    irCode.addInst(new EntryInstruction(newFunc));

    // 创建出口指令并不加入出口指令，等函数内的指令处理完毕后加入出口指令
    LabelInstruction * exitLabelInst = new LabelInstruction(newFunc);

    // 函数出口指令保存到函数信息中，因为在语义分析函数体时return语句需要跳转到函数尾部，需要这个label指令
    newFunc->setExitLabel(exitLabelInst);

    // 形参IR生成（只生成move指令）
    result = ir_function_formal_params(param_node);
    if (!result) {
        return false;
    }
    node->blockInsts.addInst(param_node->blockInsts);

    // 新建一个Value，用于保存函数的返回值，如果没有返回值可不用申请
    LocalVariable * retValue = nullptr;
    if (!retType->isVoidType()) {

        // 保存函数返回值变量到函数信息中，在return语句翻译时需要设置值到这个变量中
        retValue = static_cast<LocalVariable *>(module->newVarValue(retType));
    }
    newFunc->setReturnValue(retValue);

    // 函数内已经进入作用域，内部不再需要做变量的作用域管理
    block_node->needScope = false;

    // 遍历block
    result = ir_block(block_node);
    if (!result) {
        return false;
    }

    // IR指令追加到当前的节点中
    node->blockInsts.addInst(block_node->blockInsts);

    // 此时，所有指令都加入到当前函数中，也就是node->blockInsts

    // node节点的指令移动到函数的IR指令列表中
    irCode.addInst(node->blockInsts);

    // // 检查最后一条指令是否为终结指令，如果不是则补一个goto到exitLabel
    // auto &insts = irCode.getInsts();
    // if (!insts.empty()) {
    //     Instruction *lastInst = insts.back();
    //     if (!lastInst->isTerminator()) {
    //         irCode.addInst(new GotoInstruction(newFunc, exitLabelInst));
    //     }
    // }

    // // 添加函数出口Label指令，主要用于return语句跳转到这里进行函数的退出
    // if (!retType->isVoidType()) {
    //     irCode.addInst(exitLabelInst);
    // }
    // // 函数出口指令
    // irCode.addInst(new ExitInstruction(newFunc, retValue));
    bool needExit = !block_node->hasTerminator;

    // 如果需要统一返回
    if (needExit) {
        // if (!retType->isVoidType())
        //     irCode.addInst(exitLabelInst);
        irCode.addInst(new ExitInstruction(newFunc, retValue));
    } else {
        delete exitLabelInst; // 否则避免空标签
    }

    // 恢复成外部函数
    module->setCurrentFunction(nullptr);

    // 退出函数的作用域
    module->leaveScope();

    return true;
}

/// @brief 形式参数AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_function_formal_params(ast_node * node)
{
    Function * func = module->getCurrentFunction();
    if (!func)
        return false;

    func->getParams().clear();
    for (auto & paramNode: node->sons) {
        if (paramNode->sons.size() < 2)
            return false;

        Type * pType = nullptr;
        std::string pName = paramNode->sons[1]->name;
        // 检查是否是数组类型
        if (paramNode->sons.size() >= 3) {
            ast_node * dim_node = paramNode->sons[2];
            if (dim_node->node_type == ast_operator_type::AST_OP_ARRAY_DIM) {
                // 获取基础类型（如int）
                Type * baseType = paramNode->sons[0]->type;

                // 从dim_node获取所有维度信息（从最外层到最内层）
                std::vector<int> dimensions;
                ast_node * current_dim = dim_node;
                while (current_dim && current_dim->node_type == ast_operator_type::AST_OP_ARRAY_DIM) {
                    // 假设维度值存储在sons[0]中
                    if (current_dim->sons.size() > 0) {
                        dimensions.push_back(ir_constint_ast_node(current_dim->sons[0]));
                    }
                    current_dim = current_dim->sons.size() > 1 ? current_dim->sons[1] : nullptr;
                }

                // 从最内层到最外层构建数组类型
                Type * arrayType = baseType;
                for (auto it = dimensions.rbegin(); it != dimensions.rend(); ++it) {
                    arrayType = new PointerType(arrayType, true, *it);
                }

                // 最终创建指向这个多维数组的指针类型
                pType = new PointerType(arrayType);
            }
        }

        // 若不是数组，按正常处理
        if (!pType)
            pType = paramNode->sons[0]->type;

        // 创建 FormalParam 和 mov 指令
        FormalParam * param = new FormalParam(pType, pName);
        func->getParams().push_back(param);

        LocalVariable * localVar = static_cast<LocalVariable *>(module->newVarValue(pType, pName));
        MoveInstruction * movInst = new MoveInstruction(func, localVar, param);
        node->blockInsts.addInst(movInst);
    }
    return true;
}

/// @brief 函数调用AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_function_call(ast_node * node)
{
    std::vector<Value *> realParams;
    Function * currentFunc = module->getCurrentFunction();
    std::string funcName = node->sons[0]->name;
    ast_node * paramsNode = node->sons[1];

    // 根据函数名查找函数，看是否存在。若不存在则出错
    auto calledFunction = module->findFunction(funcName);
    calledFunction->setIsCalled(true);
    if (nullptr == calledFunction) {
        minic_log(LOG_ERROR, "函数(%s)未定义或声明", funcName.c_str());
        return false;
    }

    // 当前函数存在函数调用
    currentFunc->setExistFuncCall(true);
    // 检查是否有参数列表 且 被调用函数需要参数
    if (!paramsNode->sons.empty()) {
        int32_t argsCount = (int32_t) paramsNode->sons.size();

        // 统计实参个数
        if (argsCount > currentFunc->getMaxFuncCallArgCnt()) {
            currentFunc->setMaxFuncCallArgCnt(argsCount);
        }

        // 遍历参数列表，孩子是表达式
        for (int i = 0; i < paramsNode->sons.size(); i++) {
            auto son = paramsNode->sons[i];

            // 递归处理参数表达式
            ast_node * temp = ir_visit_ast_node(son);
            if (!temp) {
                return false;
            }

            Value * argVal = temp->val;
            Type * argType = argVal->getType();

            // 添加参数表达式的IR指令
            node->blockInsts.addInst(temp->blockInsts);

            // **关键修改：处理数组参数**
            if (argType->isPointerType() && static_cast<PointerType *>(argType)->isArray()) {
                // 数组参数：生成 getelementptr 获取首地址
                std::vector<Value *> indices = {module->newConstInt(0), module->newConstInt(0)};

                auto gepInst = new GetElementPtrInstruction(module,
                                                            currentFunc,
                                                            argVal,
                                                            indices,
                                                            static_cast<PointerType *>(argType)->getPointeeType());
                node->blockInsts.addInst(gepInst);
                argVal = gepInst->getResult();
            }

            // 获取期望的参数类型（无论是否内置函数）
            Type * expectedType = nullptr;
            if (i < calledFunction->getParams().size()) {
                expectedType = calledFunction->getParams()[i]->getType();
            }

            // 类型转换：如果实参类型与形参类型不匹配，需要转换
            if (expectedType && !argVal->getType()->equals(expectedType)) {
                CastInstruction * castInst = new CastInstruction(currentFunc, argVal, expectedType);
                node->blockInsts.addInst(castInst);
                argVal = castInst;
            }

            realParams.push_back(argVal);
        }
    }

    // 检查函数参数个数匹配
    if (!calledFunction->isBuiltin() && realParams.size() != calledFunction->getParams().size()) {
        minic_log(LOG_ERROR,
                  "第%lld行的被调用函数(%s)参数个数不匹配",
                  (long long) node->sons[0]->line_no,
                  funcName.c_str());
        return false;
    }

    // 获取返回值类型
    Type * type = calledFunction->getReturnType();

    // 创建函数调用指令
    FuncCallInstruction * funcCallInst = new FuncCallInstruction(currentFunc, calledFunction, realParams, type);
    node->blockInsts.addInst(funcCallInst);

    // 为有返回值的函数调用分配临时变量
    if (!type->isVoidType()) {
        RegVariable * retVar = currentFunc->newTempVariable(type);
        funcCallInst->setIRName(retVar->getIRName());
        node->val = funcCallInst;
    } else {
        node->val = nullptr;
    }

    return true;
}

/// @brief 语句块（含函数体）AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_block(ast_node * node)
{
    // 进入作用域
    if (node->needScope) {
        module->enterScope();
    }

    std::vector<ast_node *>::iterator pIter;
    for (pIter = node->sons.begin(); pIter != node->sons.end(); ++pIter) {
        // 遍历Block的每个语句，进行显示或者运算
        ast_node * temp = ir_visit_ast_node(*pIter);
        if (!temp) {
            return false;
        }
        node->blockInsts.addInst(temp->blockInsts);
    }

    // 离开作用域
    if (node->needScope) {
        module->leaveScope();
    }

    return true;
}

/// @brief 加法AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_add(ast_node * node)
{
    // 尝试常量折叠
    Constant * constResult = evalConstExpr1(node);
    if (constResult) {
        // 常量折叠成功，直接使用计算结果
        node->val = constResult;
        return true;
    }

    // 常量折叠失败，执行正常的加法处理
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    InterCode tmpCode;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(rightVal));
    }

    // 先插入左右子节点的 IR
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(tmpCode);

    // 再插入本节点的 IR
    BinaryInstruction * addInst = new BinaryInstruction(module->getCurrentFunction(),
                                                        IRInstOperator::IRINST_OP_ADD_I,
                                                        leftVal,
                                                        rightVal,
                                                        resultType);

    node->blockInsts.addInst(addInst);
    node->val = addInst;
    return true;
}

/// @brief 减法AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_sub(ast_node * node)
{
    // 尝试常量折叠
    Constant * constResult = evalConstExpr1(node);
    if (constResult) {
        // 常量折叠成功，直接使用计算结果
        node->val = constResult;
        return true;
    }

    // 常量折叠失败，执行正常的减法处理
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    InterCode tmpCode;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(rightVal));
    }

    // 先插入左右子节点的 IR
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(tmpCode);

    // 再插入本节点的 IR
    BinaryInstruction * subInst = new BinaryInstruction(module->getCurrentFunction(),
                                                        IRInstOperator::IRINST_OP_SUB_I,
                                                        leftVal,
                                                        rightVal,
                                                        resultType);

    node->blockInsts.addInst(subInst);
    node->val = subInst;
    return true;
}

/// @brief 乘法AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_mul(ast_node * node)
{
    // 尝试常量折叠
    Constant * constResult = evalConstExpr1(node);
    if (constResult) {
        // 常量折叠成功，直接使用计算结果
        node->val = constResult;
        return true;
    }

    // 常量折叠失败，执行正常的乘法处理
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    InterCode tmpCode;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(rightVal));
    }

    // 先插入左右子节点的 IR
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(tmpCode);

    // 再插入本节点的 IR
    BinaryInstruction * mulInst = new BinaryInstruction(module->getCurrentFunction(),
                                                        IRInstOperator::IRINST_OP_MUL_I,
                                                        leftVal,
                                                        rightVal,
                                                        resultType);
    node->blockInsts.addInst(mulInst);

    node->val = mulInst;
    return true;
}

/// @brief 除法AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_div(ast_node * node)
{
    // 尝试常量折叠
    Constant * constResult = evalConstExpr1(node);
    if (constResult) {
        // 常量折叠成功，直接使用计算结果
        node->val = constResult;
        return true;
    }

    // 常量折叠失败，执行正常的除法处理
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    InterCode tmpCode;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        tmpCode.addInst(static_cast<Instruction *>(rightVal));
    }

    // 先插入左右子节点的 IR
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(tmpCode);

    // 再插入本节点的 IR
    BinaryInstruction * divInst = new BinaryInstruction(module->getCurrentFunction(),
                                                        IRInstOperator::IRINST_OP_DIV_I,
                                                        leftVal,
                                                        rightVal,
                                                        resultType);

    node->blockInsts.addInst(divInst);
    node->val = divInst;
    return true;
}

/// @brief 整数取余AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_mod(ast_node * node)
{
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];
    // 尝试常量折叠
    Constant * constResult = evalConstExpr1(node);
    if (constResult) {
        // 常量折叠成功，直接使用计算结果
        node->val = constResult;
        return true;
    }

    // 加法节点，左结合，先计算左节点，后计算右节点

    // 左边操作数
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left) {
        // 某个变量没有定值
        return false;
    }

    // 右边操作数
    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right) {
        // 某个变量没有定值
        return false;
    }

    // 这里只处理整型的数据，如需支持实数，则需要针对类型进行处理
    // TODO real number add

    BinaryInstruction * modInst = new BinaryInstruction(module->getCurrentFunction(),
                                                        IRInstOperator::IRINST_OP_MOD_I,
                                                        left->val,
                                                        right->val,
                                                        IntegerType::getTypeInt());

    // 创建临时变量保存IR的值，以及线性IR指令
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(modInst);

    node->val = modInst;

    return true;
}

/// @brief 小于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_less(ast_node * node)
{
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    // 左边操作数
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    // 右边操作数
    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(rightVal));
    }

    // 创建比较指令
    BinaryInstruction * lessInst = new BinaryInstruction(module->getCurrentFunction(),
                                                         IRInstOperator::IRINST_OP_LESS_I,
                                                         leftVal,
                                                         rightVal,
                                                         IntegerType::getTypeBool());

    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(lessInst);

    node->val = lessInst;
    return true;
}

/// @brief 小于等于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_less_equal(ast_node * node)
{
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    // 左边操作数
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    // 右边操作数
    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(rightVal));
    }

    // 创建比较指令
    BinaryInstruction * lessEqualInst = new BinaryInstruction(module->getCurrentFunction(),
                                                              IRInstOperator::IRINST_OP_LESS_EQUAL_I,
                                                              leftVal,
                                                              rightVal,
                                                              IntegerType::getTypeBool());

    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(lessEqualInst);

    node->val = lessEqualInst;
    return true;
}

/// @brief 大于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_greater(ast_node * node)
{
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    // 左边操作数
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    // 右边操作数
    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(rightVal));
    }

    // 创建比较指令
    BinaryInstruction * greaterInst = new BinaryInstruction(module->getCurrentFunction(),
                                                            IRInstOperator::IRINST_OP_GREATER_I,
                                                            leftVal,
                                                            rightVal,
                                                            IntegerType::getTypeBool());

    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(greaterInst);

    node->val = greaterInst;
    return true;
}

/// @brief 大于等于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_greater_equal(ast_node * node)
{
    ast_node * src1_node = node->sons[0];
    ast_node * src2_node = node->sons[1];

    // 左边操作数
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    // 右边操作数
    ast_node * right = ir_visit_ast_node(src2_node);
    if (!right)
        return false;

    // 类型推导
    Type * resultType = (left->val->getType()->isFloatType() || right->val->getType()->isFloatType())
                            ? FloatType::getTypeFloat()
                            : IntegerType::getTypeInt();
    if (!resultType)
        return false;

    // 类型转换
    Value * leftVal = left->val;
    Value * rightVal = right->val;
    if (leftVal->getType() != resultType) {
        leftVal = new CastInstruction(module->getCurrentFunction(), leftVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(leftVal));
    }
    if (rightVal->getType() != resultType) {
        rightVal = new CastInstruction(module->getCurrentFunction(), rightVal, resultType);
        node->blockInsts.addInst(static_cast<Instruction *>(rightVal));
    }

    // 创建比较指令
    BinaryInstruction * greaterEqualInst = new BinaryInstruction(module->getCurrentFunction(),
                                                                 IRInstOperator::IRINST_OP_GREATER_EQUAL_I,
                                                                 leftVal,
                                                                 rightVal,
                                                                 IntegerType::getTypeBool());

    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(greaterEqualInst);

    node->val = greaterEqualInst;
    return true;
}

/// @brief 等于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_eq(ast_node * node)
{
    // 递归生成左右子表达式IR
    ast_node * left_node = ir_visit_ast_node(node->sons[0]);
    ast_node * right_node = ir_visit_ast_node(node->sons[1]);
    if (!left_node || !right_node)
        return false;

    node->blockInsts.addInst(left_node->blockInsts);
    node->blockInsts.addInst(right_node->blockInsts);

    Value * left_val = left_node->val;
    Value * right_val = right_node->val;

    // 类型对齐
    Type * targetType = nullptr;
    if (left_val->getType()->isFloatType() || right_val->getType()->isFloatType()) {
        targetType = FloatType::getTypeFloat();
    } else {
        targetType = IntegerType::getTypeInt();
    }
    if (left_val->getType() != targetType) {
        CastInstruction * castInst = new CastInstruction(module->getCurrentFunction(), left_val, targetType);
        node->blockInsts.addInst(castInst);
        left_val = castInst;
    }
    if (right_val->getType() != targetType) {
        CastInstruction * castInst = new CastInstruction(module->getCurrentFunction(), right_val, targetType);
        node->blockInsts.addInst(castInst);
        right_val = castInst;
    }

    // 生成比较指令
    Function * func = module->getCurrentFunction();
    BinaryInstruction * eqInst =
        new BinaryInstruction(func, IRInstOperator::IRINST_OP_EQ_I, left_val, right_val, IntegerType::getTypeBool());
    node->blockInsts.addInst(eqInst);
    node->val = eqInst;
    return true;
}

/// @brief 不等于AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_neq(ast_node * node)
{
    // 递归生成左右子表达式IR
    ast_node * left_node = ir_visit_ast_node(node->sons[0]);
    ast_node * right_node = ir_visit_ast_node(node->sons[1]);
    if (!left_node || !right_node)
        return false;

    node->blockInsts.addInst(left_node->blockInsts);
    node->blockInsts.addInst(right_node->blockInsts);

    Value * left_val = left_node->val;
    Value * right_val = right_node->val;

    // 类型对齐
    Type * targetType = nullptr;
    if (left_val->getType()->isFloatType() || right_val->getType()->isFloatType()) {
        targetType = FloatType::getTypeFloat();
    } else {
        targetType = IntegerType::getTypeInt();
    }
    if (left_val->getType() != targetType) {
        CastInstruction * castInst = new CastInstruction(module->getCurrentFunction(), left_val, targetType);
        node->blockInsts.addInst(castInst);
        left_val = castInst;
    }
    if (right_val->getType() != targetType) {
        CastInstruction * castInst = new CastInstruction(module->getCurrentFunction(), right_val, targetType);
        node->blockInsts.addInst(castInst);
        right_val = castInst;
    }

    // 生成比较指令
    Function * func = module->getCurrentFunction();
    BinaryInstruction * neqInst =
        new BinaryInstruction(func, IRInstOperator::IRINST_OP_NEQ_I, left_val, right_val, IntegerType::getTypeBool());
    node->blockInsts.addInst(neqInst);
    node->val = neqInst;
    return true;
}

// 用于 map 的默认版本
bool IRGenerator::ir_land(ast_node * node)
{
    Function * func = module->getCurrentFunction();

    // 创建中间 label 和最终结果变量
    LabelInstruction * rhsLabel = new LabelInstruction(func);
    LabelInstruction * endLabel = new LabelInstruction(func);
    RegVariable * result = func->newTempVariable(IntegerType::getTypeBool());

    // 1. 左子表达式
    ast_node * lhs = ir_visit_ast_node(node->sons[0]);
    if (!lhs)
        return false;
    node->blockInsts.addInst(lhs->blockInsts);

    Value * lhs_val = lhs->val;
    // --- 新增：float类型条件转换为i1 ---
    lhs_val = convertToBool(lhs, lhs_val, node->blockInsts);

    // 2. CondGoto: 为 true 跳转到 rhsLabel 继续判断，为 false 则 result = false
    node->blockInsts.addInst(new CondGotoInstruction(func, lhs_val, rhsLabel, endLabel));
    node->blockInsts.addInst(new MoveInstruction(func, result, module->newConstInt(0)));
    node->blockInsts.addInst(new GotoInstruction(func, endLabel));

    // 3. 右子表达式
    node->blockInsts.addInst(rhsLabel);

    ast_node * rhs = ir_visit_ast_node(node->sons[1]);
    if (!rhs)
        return false;
    node->blockInsts.addInst(rhs->blockInsts);

    Value * rhs_val = rhs->val;
    // --- 新增：float类型条件转换为i1 ---
    rhs_val = convertToBool(rhs, rhs_val, node->blockInsts);

    node->blockInsts.addInst(new MoveInstruction(func, result, rhs_val));

    // 4. 结束
    node->blockInsts.addInst(endLabel);
    node->val = result;
    return true;
}

// 支持连续&&嵌套的短路逻辑版本
bool IRGenerator::ir_land(ast_node * node, LabelInstruction * true_label, LabelInstruction * false_label)
{
    Function * func = module->getCurrentFunction();
    if (!func)
        return false;

    // 处理左子树
    ast_node * lhs = node->sons[0];
    if (lhs->node_type == ast_operator_type::AST_OP_LAND) {
        // 为当前条件创建新的标签
        LabelInstruction * mid_label = new LabelInstruction(func);
        if (!ir_land(lhs, mid_label, false_label))
            return false;
        node->blockInsts.addInst(lhs->blockInsts);
        node->blockInsts.addInst(mid_label);
    } else if (lhs->node_type == ast_operator_type::AST_OP_LOR) {
        // 处理逻辑或
        if (!ir_lor(lhs, true_label, false_label))
            return false;
        node->blockInsts.addInst(lhs->blockInsts);
    } else {
        lhs = ir_visit_ast_node(lhs);
        if (!lhs)
            return false;
        node->blockInsts.addInst(lhs->blockInsts);

        Value * lhs_val = lhs->val;
        // --- 新增：float类型条件转换为i1 ---
        lhs_val = convertToBool(lhs, lhs_val, node->blockInsts);

        // 为当前条件创建新的标签
        LabelInstruction * mid_label = new LabelInstruction(func);
        node->blockInsts.addInst(new CondGotoInstruction(func, lhs_val, mid_label, false_label));
        node->blockInsts.addInst(mid_label);
    }

    // 处理右子树
    ast_node * rhs = node->sons[1];
    if (rhs->node_type == ast_operator_type::AST_OP_LAND) {
        // 递归处理连续的逻辑与
        if (!ir_land(rhs, true_label, false_label))
            return false;
        node->blockInsts.addInst(rhs->blockInsts);
    } else if (rhs->node_type == ast_operator_type::AST_OP_LOR) {
        // 处理逻辑或
        if (!ir_lor(rhs, true_label, false_label))
            return false;
        node->blockInsts.addInst(rhs->blockInsts);
    } else {
        rhs = ir_visit_ast_node(rhs);
        if (!rhs)
            return false;
        node->blockInsts.addInst(rhs->blockInsts);

        Value * rhs_val = rhs->val;
        // --- 新增：float类型条件转换为i1 ---
        rhs_val = convertToBool(rhs, rhs_val, node->blockInsts);

        // 最终条件直接跳转到true_label或false_label
        node->blockInsts.addInst(new CondGotoInstruction(func, rhs_val, true_label, false_label));
    }

    return true;
}

/// @brief 逻辑或AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_lor(ast_node * node)
{
    Function * func = module->getCurrentFunction();
    if (!func)
        return false;

    ast_node * lhs_node = ir_visit_ast_node(node->sons[0]);
    ast_node * rhs_node = node->sons[1];

    if (!lhs_node)
        return false;
    node->blockInsts.addInst(lhs_node->blockInsts);

    Value * lhs_val = lhs_node->val;
    // --- 修改：统一用 convertToBool ---
    lhs_val = convertToBool(lhs_node, lhs_val, node->blockInsts);

    // 标签：rhsLabel 表示左为假才跳转；endLabel 结束；truePathLabel 表示左为真时直接返回 true
    LabelInstruction * rhsLabel = new LabelInstruction(func);
    LabelInstruction * trueLabel = new LabelInstruction(func);
    LabelInstruction * endLabel = new LabelInstruction(func);

    // 结果变量
    RegVariable * result = func->newTempVariable(IntegerType::getTypeBool());

    // 条件跳转：若 lhs 为 true 则跳转 trueLabel，否则跳转 rhsLabel
    node->blockInsts.addInst(new CondGotoInstruction(func, lhs_val, trueLabel, rhsLabel));

    // rhsLabel：左为假，进入右表达式
    node->blockInsts.addInst(rhsLabel);
    ast_node * rhs_eval = ir_visit_ast_node(rhs_node);
    if (!rhs_eval)
        return false;
    node->blockInsts.addInst(rhs_eval->blockInsts);

    Value * rhs_val = rhs_eval->val;
    // --- 修改：统一用 convertToBool ---
    rhs_val = convertToBool(rhs_eval, rhs_val, node->blockInsts);

    node->blockInsts.addInst(new MoveInstruction(func, result, rhs_val));
    node->blockInsts.addInst(new GotoInstruction(func, endLabel));

    // trueLabel：直接返回 true
    node->blockInsts.addInst(trueLabel);
    node->blockInsts.addInst(new MoveInstruction(func, result, module->newConstInt(1)));
    node->blockInsts.addInst(new GotoInstruction(func, endLabel));

    // endLabel
    node->blockInsts.addInst(endLabel);
    node->val = result;

    return true;
}

// 短路逻辑实现：true_label为前一项为真时跳转，false_label为所有为假时跳转
bool IRGenerator::ir_lor(ast_node * node, LabelInstruction * true_label, LabelInstruction * false_label)
{
    Function * func = module->getCurrentFunction();

    // 处理左子树
    ast_node * lhs = node->sons[0];
    if (lhs->node_type == ast_operator_type::AST_OP_LOR) {
        // 左子树是||表达式
        LabelInstruction * mid_label = new LabelInstruction(func);
        if (!ir_lor(lhs, true_label, mid_label))
            return false;
        node->blockInsts.addInst(lhs->blockInsts);
        node->blockInsts.addInst(mid_label);
    } else if (lhs->node_type == ast_operator_type::AST_OP_LAND) {
        // 左子树是&&表达式 - 新增处理
        LabelInstruction * land_true_label = new LabelInstruction(func);
        if (!ir_land(lhs, true_label, land_true_label))
            return false;
        node->blockInsts.addInst(lhs->blockInsts);
        node->blockInsts.addInst(land_true_label);
    } else {
        lhs = ir_visit_ast_node(lhs);
        if (!lhs)
            return false;
        node->blockInsts.addInst(lhs->blockInsts);

        Value * lhs_val = lhs->val;
        // --- 新增：float类型条件转换为i1 ---
        // --- 修改：统一用 convertToBool ---
        lhs_val = convertToBool(lhs, lhs_val, node->blockInsts);

        // 为右子树准备新标签
        LabelInstruction * rhs_label = new LabelInstruction(func);
        node->blockInsts.addInst(new CondGotoInstruction(func, lhs_val, true_label, rhs_label));
        node->blockInsts.addInst(rhs_label);
    }

    // 处理右子树
    ast_node * rhs = node->sons[1];
    if (rhs->node_type == ast_operator_type::AST_OP_LOR) {
        if (!ir_lor(rhs, true_label, false_label))
            return false;
        node->blockInsts.addInst(rhs->blockInsts);
    } else if (rhs->node_type == ast_operator_type::AST_OP_LAND) {
        // 处理逻辑与
        if (!ir_land(rhs, true_label, false_label))
            return false;
        node->blockInsts.addInst(rhs->blockInsts);
    } else {
        rhs = ir_visit_ast_node(rhs);
        if (!rhs)
            return false;
        node->blockInsts.addInst(rhs->blockInsts);

        Value * rhs_val = rhs->val;
        // --- 新增：float类型条件转换为i1 ---
        // --- 修改：统一用 convertToBool ---
        rhs_val = convertToBool(rhs, rhs_val, node->blockInsts);

        node->blockInsts.addInst(new CondGotoInstruction(func, rhs_val, true_label, false_label));
    }

    return true;
}

/// @brief 逻辑非AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_lnot(ast_node * node)
{
    ast_node * src1_node = node->sons[0];

    // 先递归访问子节点
    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left)
        return false;

    Function * func = module->getCurrentFunction();
    Value * operand = left->val;

    // 添加子节点指令
    node->blockInsts.addInst(left->blockInsts);

    // 1. 先生成单目运算指令（逻辑非）
    SingleInstruction * lnotInst =
        new SingleInstruction(func, IRInstOperator::IRINST_OP_LNOT_I, operand, IntegerType::getTypeBool());
    node->blockInsts.addInst(lnotInst);

    // 2. 如有需要，再做类型转换
    Value * result = lnotInst;
    Type * expectType = operand->getType()->isFloatType() ? FloatType::getTypeFloat() : IntegerType::getTypeInt();
    if (lnotInst->getType() != expectType) {
        CastInstruction * castInst = new CastInstruction(func, lnotInst, expectType);
        node->blockInsts.addInst(castInst);
        result = castInst;
    }

    node->val = result;
    return true;
}

/// @brief minus AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_unary_minus(ast_node * node)
{
    ast_node * src1_node = node->sons[0];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left) {
        return false;
    }

    Function * func = module->getCurrentFunction();
    Value * operand = left->val;

    node->blockInsts.addInst(left->blockInsts);

    // 1. 先生成单目运算指令
    SingleInstruction * negInst =
        new SingleInstruction(func, IRInstOperator::IRINST_OP_UNARY_MINUS_I, operand, operand->getType());
    node->blockInsts.addInst(negInst);

    // 2. 如有需要，再做类型转换
    Value * result = negInst;
    Type * expectType = operand->getType()->isFloatType() ? FloatType::getTypeFloat() : IntegerType::getTypeInt();
    if (negInst->getType() != expectType) {
        CastInstruction * castInst = new CastInstruction(func, negInst, expectType);
        node->blockInsts.addInst(castInst);
        result = castInst;
    }

    node->val = result;
    return true;
}

/// @brief plus AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_unary_plus(ast_node * node)
{
    ast_node * src1_node = node->sons[0];

    ast_node * left = ir_visit_ast_node(src1_node);
    if (!left) {
        return false;
    }

    Function * func = module->getCurrentFunction();
    Value * operand = left->val;

    node->blockInsts.addInst(left->blockInsts);

    // 1. 先生成单目运算指令
    SingleInstruction * posInst =
        new SingleInstruction(func, IRInstOperator::IRINST_OP_UNARY_PLUS_I, operand, operand->getType());
    node->blockInsts.addInst(posInst);

    // 2. 如有需要，再做类型转换
    Value * result = posInst;
    Type * expectType = operand->getType()->isFloatType() ? FloatType::getTypeFloat() : IntegerType::getTypeInt();
    if (posInst->getType() != expectType) {
        CastInstruction * castInst = new CastInstruction(func, posInst, expectType);
        node->blockInsts.addInst(castInst);
        result = castInst;
    }

    node->val = result;
    return true;
}

/// @brief 赋值AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_assign(ast_node * node)
{
    ast_node * lhsNode = node->sons[0];
    ast_node * rhsNode = node->sons[1];

    // 1. 生成右值 IR
    ast_node * rhs = ir_visit_ast_node(rhsNode);
    if (!rhs || !rhs->val)
        return false;

    // 2. 生成左值 IR（包括 GEP + load）
    ast_node * lhs = ir_visit_ast_node(lhsNode);
    if (!lhs)
        return false;

    // 3. 将左值的 IR 加入
    node->blockInsts.addInst(lhs->blockInsts);

    // 4. 识别目标地址
    Value * ptr = nullptr;
    if (lhsNode->node_type == ast_operator_type::AST_OP_ARRAY_ACCESS) {
        auto & seq = node->blockInsts.getInsts();
        Instruction * last = seq.back();
        seq.pop_back(); // 移除 load
        delete last;
        ptr = static_cast<GetElementPtrInstruction *>(seq.back())->getResult();
    } else {
        ptr = lhs->val;
    }

    // 5. 准备类型信息
    Type * srcT = rhs->val->getType();
    Type * dstT = ptr->getType()->isPointerType()
                      ? const_cast<Type *>(static_cast<PointerType *>(ptr->getType())->getPointeeType())
                      : ptr->getType();

    // 6+7. 详细类型转换：按原格式插入 rhs／lhs IR，再插入 Cast 或直接插入
    Value * valToStore = rhs->val;
    if (srcT && dstT && srcT != dstT && !srcT->equals(dstT)) {
        RegVariable * castVar = module->getCurrentFunction()->newTempVariable(dstT);
        CastInstruction * castInst = nullptr;
        if (srcT->isFloatType() && dstT->isInt32Type()) {
            // float 到 int 的转换，使用 fptosi
            castInst = new CastInstruction(module->getCurrentFunction(), rhs->val, dstT);
        } else if (srcT->isInt32Type() && dstT->isFloatType()) {
            // int 到 float 的转换，使用 sitofp
            castInst = new CastInstruction(module->getCurrentFunction(), rhs->val, dstT);
        } else if (srcT->isInt32Type() && dstT->isInt1Byte()) {
            // int 到 bool 的转换
            castInst = new CastInstruction(module->getCurrentFunction(), rhs->val, dstT);
        } else if (srcT->isInt1Byte() && dstT->isInt32Type()) {
            // bool 到 int 的转换
            castInst = new CastInstruction(module->getCurrentFunction(), rhs->val, dstT);
        } else {
            // 其他类型转换
            castInst = new CastInstruction(module->getCurrentFunction(), rhs->val, dstT);
        }
        castInst->setIRName(castVar->getIRName());
        node->blockInsts.addInst(rhs->blockInsts);
        node->blockInsts.addInst(lhs->blockInsts);
        node->blockInsts.addInst(castInst);
        valToStore = castInst;
    } else {
        node->blockInsts.addInst(rhs->blockInsts);
        node->blockInsts.addInst(lhs->blockInsts);
    }

    // 8. 生成最终赋值指令
    if (lhsNode->node_type == ast_operator_type::AST_OP_ARRAY_ACCESS) {
        node->blockInsts.addInst(new StoreInstruction(module->getCurrentFunction(), ptr, valToStore));
        node->val = ptr;
    } else {
        MoveInstruction * mi = new MoveInstruction(module->getCurrentFunction(), ptr, valToStore);
        node->blockInsts.addInst(mi);
        node->val = mi;
    }
    return true;
}

/// @brief 变量初始化赋值AST节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_init(ast_node * node)
{
    ast_node * son1_node = node->sons[0];
    ast_node * son2_node = node->sons[1];

    // 处理左值
    ast_node * left = ir_visit_ast_node(son1_node);
    if (!left || !left->val) {
        minic_log(LOG_ERROR, "左值初始化失败");
        return false;
    }

    // +++ 新增：特殊处理负号表达式 +++
    if (son2_node->node_type == ast_operator_type::AST_OP_UNARY_MINUS) {
        // 递归处理负号表达式
        ast_node * right = ir_visit_ast_node(son2_node);
        if (!right || !right->val) {
            minic_log(LOG_ERROR, "负号表达式处理失败");
            return false;
        }

        // 添加所有指令
        node->blockInsts.addInst(left->blockInsts);
        node->blockInsts.addInst(right->blockInsts);

        // 创建赋值指令
        MoveInstruction * movInst = new MoveInstruction(module->getCurrentFunction(), left->val, right->val);
        node->blockInsts.addInst(movInst);
        node->val = movInst;
        return true;
    }

    // 原有处理逻辑（普通表达式）
    ast_node * right = ir_visit_ast_node(son2_node);
    if (!right || !right->val) {
        minic_log(LOG_ERROR, "右值初始化失败");
        return false;
    }

    // 创建赋值指令
    MoveInstruction * movInst = new MoveInstruction(module->getCurrentFunction(), left->val, right->val);

    // 添加指令
    node->blockInsts.addInst(left->blockInsts);
    node->blockInsts.addInst(right->blockInsts);
    node->blockInsts.addInst(movInst);

    node->val = movInst;
    return true;
}

/// @brief return节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_return(ast_node * node)
{
    ast_node * right = nullptr;

    // return语句可能没有表达式，也可能有，因此这里必须进行区分判断
    if (!node->sons.empty()) {
        ast_node * son_node = node->sons[0];
        right = ir_visit_ast_node(son_node);
        if (!right) {
            return false;
        }
    }

    Function * currentFunc = module->getCurrentFunction();

    // 如果有返回值，将其存储到函数的返回值变量中
    if (right && currentFunc->getReturnValue()) {
        node->blockInsts.addInst(right->blockInsts);
        node->blockInsts.addInst(new MoveInstruction(currentFunc, currentFunc->getReturnValue(), right->val));
    }

    node->blockInsts.addInst(new ExitInstruction(currentFunc, currentFunc->getReturnValue()));
    node->parent->hasTerminator = true; // 标记该节点包含终结指令

    return true;
}

/// @brief if语句节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_if(ast_node * node)
{
    // node->sons[0]: 条件表达式
    // node->sons[1]: then 块
    // node->sons[2]: else 块（可选）

    ast_node * cond = node->sons[0];

    Function * func = module->getCurrentFunction();

    // 1. 创建标签
    LabelInstruction * thenLabel = new LabelInstruction(func);
    LabelInstruction * endLabel = new LabelInstruction(func);
    LabelInstruction * elseLabel = nullptr;

    bool hasElse =
        node->sons.size() > 2 || (node->sons.size() == 2 && node->sons[1]->node_type == ast_operator_type::AST_OP_ELSE);
    if (hasElse) {
        elseLabel = new LabelInstruction(func);
    }

    // 2. 判断是否为短路逻辑表达式（如 a && b）
    if (cond->node_type == ast_operator_type::AST_OP_LAND) {
        if (!ir_land(cond, thenLabel, hasElse ? elseLabel : endLabel))
            return false;

        node->blockInsts.addInst(cond->blockInsts);

    } else if (cond->node_type == ast_operator_type::AST_OP_LOR) {
        if (!ir_lor(cond, thenLabel, hasElse ? elseLabel : endLabel))
            return false;
        node->blockInsts.addInst(cond->blockInsts);
    } else {
        // 非短路表达式
        ast_node * condNode = ir_visit_ast_node(cond);
        if (!condNode)
            return false;
        node->blockInsts.addInst(condNode->blockInsts);

        Value * condVal = condNode->val;
        condVal = convertToBool(condNode, condVal, node->blockInsts);

        node->blockInsts.addInst(new CondGotoInstruction(func, condVal, thenLabel, hasElse ? elseLabel : endLabel));
    }

    // 3. then 分支
    node->blockInsts.addInst(thenLabel);
    ast_node * thenBlock = node->sons.size() > 1 ? node->sons[1] : nullptr;
    bool thenTerminates = false;
    if (thenBlock) {
        if (!ir_visit_ast_node(thenBlock))
            return false;
        node->blockInsts.addInst(thenBlock->blockInsts);

        auto & insts = thenBlock->blockInsts.getInsts();
        thenTerminates = !insts.empty() && insts.back()->isTerminator();
        if (!thenTerminates) {
            node->blockInsts.addInst(new GotoInstruction(func, endLabel));
        }
    } else {
        node->blockInsts.addInst(new GotoInstruction(func, endLabel));
    }

    // 4. else 分支
    bool elseTerminates = false;
    if (hasElse) {
        node->blockInsts.addInst(elseLabel);
        ast_node * elseBlock = node->sons.size() > 2 ? node->sons[2] : node->sons[1];
        if (!ir_visit_ast_node(elseBlock))
            return false;
        node->blockInsts.addInst(elseBlock->blockInsts);

        auto & insts = elseBlock->blockInsts.getInsts();
        elseTerminates = !insts.empty() && insts.back()->isTerminator();
        if (!elseTerminates) {
            node->blockInsts.addInst(new GotoInstruction(func, endLabel));
        }
    }

    // 5. 加 endLabel（如果不是两边都 return）
    if (!(thenTerminates && (hasElse ? elseTerminates : true))) {
        node->blockInsts.addInst(endLabel);
    } else {
        // 如果所有分支都是终结指令，删除不必要的endLabel
        delete endLabel;
    }

    return true;
}

bool IRGenerator::ir_else(ast_node * node)
{
    // node结构: node->sons[0]是else块或嵌套的if或单条语句或空块
    // 如果是空块，则不需要处理，直接返回true

    if (node->sons.size() == 0) {
        // 空else块，不返回false，让上级处理跳转到endlabel
        return true;
    }

    ast_node * elseContent = node->sons[0];

    if (elseContent->node_type == ast_operator_type::AST_OP_IF) {
        // 处理嵌套的if
        ast_node * nestedIf = ir_visit_ast_node(elseContent);
        if (!nestedIf) {
            return false;
        }
        node->blockInsts.addInst(nestedIf->blockInsts);
    } else {
        // 处理else块
        ast_node * elseblock = ir_visit_ast_node(elseContent);
        if (!elseblock) {
            return false;
        }
        node->blockInsts.addInst(elseblock->blockInsts);
    }
    return true;
}

/// @brief 类型叶子节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_leaf_node_type(ast_node * node)
{
    // 对于类型节点，将内部的type直接赋值到val，确保后续能取到正确类型
    if (node->type == nullptr) {
        printf("错误：类型节点未设置 type 信息，位置：第 %lld 行\n", (long long) node->line_no);
        return false;
    }
    node->val = reinterpret_cast<Value *>(node->type);
    return true;
}

/// @brief 变量ID叶节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_leaf_node_var_id(ast_node * node)
{
    // 首先查找变量
    Value * val = module->findVarValue(node->name);
    if (val) {
        node->val = val;
        return true;
    }

    // 如果找不到变量，检查是否是函数名
    Function * func = module->findFunction(node->name);
    if (func) {
        // 将函数作为函数指针使用
        node->val = func;
        return true;
    }

    minic_log(LOG_ERROR, "第%lld行变量或函数%s未定义", (long long) node->line_no, node->name.c_str());
    return false;
}

/// @brief 无符号整数字面量叶子节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_leaf_node_uint(ast_node * node)
{
    ConstInt * val;

    // 新建一个整数常量Value
    val = module->newConstInt((int32_t) node->integer_val);

    node->val = val;

    return true;
}

/// @brief float数字面量叶子节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_leaf_node_float(ast_node * node)
{
    ConstFloat * val;

    // 新建一个浮点数常量Value
    val = module->newConstFloat(node->float_val);

    node->val = val;

    return true;
}

/// @brief 变量声明语句节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_declare_statment(ast_node * node)
{
    bool result = false;
    for (auto & child: node->sons) {
        result = ir_visit_ast_node(child);
        node->blockInsts.addInst(child->blockInsts);
        if (!result) {
            break;
        }
    }

    return result;
}

/// @brief 变量定声明节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_variable_declare(ast_node * node)
{
    // 共有两个孩子，第一个是类型，第二个是变量名，可能还有第三个是初始化表达式
    ast_node * typeNode = node->sons[0];
    ast_node * varNode = node->sons[1];

    // 如果当前不在函数内，则为全局变量
    if (!module->getCurrentFunction()) {
        // 处理全局变量 - 全局变量不允许遮蔽
        if (varNode->node_type == ast_operator_type::AST_OP_VAR_INIT) {
            std::string varName = varNode->sons[0]->name;

            // 检查全局变量是否已存在
            if (module->findGlobalVariable(varName)) {
                minic_log(LOG_ERROR, "全局变量(%s)已经存在", varName.c_str());
                return false;
            }

            ast_node * initExpr = varNode->sons[1];

            // 静态求值
            ir_visit_ast_node(initExpr); // 必须先 visit，确保 expr->val 被填充
            Constant * constVal = evalConstExpr(initExpr);
            if (!constVal) {
                minic_log(LOG_ERROR, "全局变量初始化表达式必须是常量");
                return false;
            }

            // 创建全局变量
            GlobalVariable * globalVar = module->newGlobalVariable(typeNode->type, varName, constVal);
            node->val = globalVar;

            module->enterScope();
            module->leaveScope();
        } else {
            // 没有初始化表达式，创建未初始化的全局变量
            std::string varName = varNode->name;

            // 检查全局变量是否已存在
            if (module->findGlobalVariable(varName)) {
                minic_log(LOG_ERROR, "全局变量(%s)已经存在", varName.c_str());
                return false;
            }

            GlobalVariable * globalVar = module->newGlobalVariable(typeNode->type, varName);
            node->val = globalVar;
            module->enterScope();
            module->leaveScope();
        }
    } else {
        // 处理局部变量 - 局部变量允许遮蔽
        if (varNode->node_type == ast_operator_type::AST_OP_VAR_INIT) {
            // 允许遮蔽：在当前作用域创建新变量，即使外层有同名变量
            Value * var = module->newVarValue(typeNode->type, varNode->sons[0]->name, true);
            if (!var) {
                return false;
            }
            node->val = var;
            varNode->val = var; // 让左值能引用到这个变量
            if (!ir_visit_ast_node(varNode)) {
                return false;
            }
            node->blockInsts.addInst(varNode->blockInsts);
        } else {
            // 允许遮蔽：在当前作用域创建新变量
            Value * var = module->newVarValue(typeNode->type, varNode->name, true);
            if (!var) {
                return false;
            }
            node->val = var;
        }
    }

    return true;
}

/// @brief 常量声明节点IR生成：遍历所有常量定义节点
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_const_decl(ast_node * node)
{
    bool result = true;
    for (auto & child: node->sons) {
        if (child->node_type != ast_operator_type::AST_OP_CONST_DEF) {
            continue;
        }
        result = ir_const_def(child);
        node->blockInsts.addInst(child->blockInsts);
        if (!result)
            break;
    }
    return result;
}

/// @brief 常量定义节点IR生成：支持变量遮蔽
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_const_def(ast_node * node)
{
    // 确保节点和子节点数量有效
    if (!node || (node->sons.size() < 2 && node->sons[0]->node_type != ast_operator_type::AST_OP_ARRAY_DECL)) {
        return false;
    }

    if (node->sons.size() == 1 && node->sons[0]->node_type == ast_operator_type::AST_OP_ARRAY_DECL) {
        ir_visit_ast_node(node->sons[0]);
        node->blockInsts.addInst(node->sons[0]->blockInsts);
        return true;
    }

    // 获取常量名节点和常量值节点
    ast_node * nameNode = node->sons[0];
    ast_node * valueNode = node->sons[1];

    if (!nameNode || !valueNode) {
        return false;
    }

    // 常量表达式求值
    Value * constVal = nullptr;
    if (valueNode->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_UINT) {
        constVal = module->newConstInt((int32_t) valueNode->integer_val);
    } else if (valueNode->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT) {
        constVal = module->newConstFloat(valueNode->float_val);
    } else {
        // 处理复杂常量表达式
        if (node->parent && node->parent->sons.size() > 0) {
            Type * constType = node->parent->sons[0]->type;
            if (constType->isInt32Type()) {
                int val = ir_constint_ast_node(valueNode);
                constVal = module->newConstInt(val);
            } else if (constType->isFloatType()) {
                float val = ir_constfloat_ast_node(valueNode);
                constVal = module->newConstFloat(val);
            } else {
                minic_log(LOG_ERROR, "不支持的常量类型");
                return false;
            }
        } else {
            minic_log(LOG_ERROR, "无法确定常量类型");
            return false;
        }
    }

    node->val = constVal;

    // 注册到符号表 - 允许在新作用域中遮蔽外层常量
    if (nameNode->name.empty()) {
        minic_log(LOG_ERROR, "常量名不能为空");
        return false;
    }

    // 对于常量，我们需要创建一个实际的变量来存储值，以支持作用域遮蔽
    if (module->getCurrentFunction()) {
        // 在函数内，创建局部常量变量（允许遮蔽）
        Type * constType = constVal->getType();
        Value * constVar = module->newVarValue(constType, nameNode->name, true);
        if (!constVar) {
            return false;
        }

        // 生成初始化指令
        MoveInstruction * initInst = new MoveInstruction(module->getCurrentFunction(), constVar, constVal);
        node->blockInsts.addInst(initInst);
        node->val = constVar;
    } else {
        // 全局常量，注册到常量表
        module->addConstValue(nameNode->name, constVal);
    }

    return true;
}

/// @brief while语句节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_while(ast_node * node)
{
    // node->sons[0]: 条件
    // node->sons[1]: 循环体

    Function * func = module->getCurrentFunction();

    // 1. 创建标签
    LabelInstruction * condLabel = new LabelInstruction(func);
    LabelInstruction * bodyLabel = new LabelInstruction(func);
    LabelInstruction * endLabel = new LabelInstruction(func);

    // 2. 将循环的出口标签和继续标签压栈
    breakTargetLabels.push_back(endLabel);
    continueTargetLabels.push_back(condLabel);

    // 3. 初始跳转到 condLabel
    node->blockInsts.addInst(new GotoInstruction(func, condLabel));
    node->blockInsts.addInst(condLabel);

    ast_node * cond = node->sons[0];
    bool isShortCircuit = false;

    // 4. 处理循环条件，考虑短路逻辑
    if (cond->node_type == ast_operator_type::AST_OP_LAND) {
        LabelInstruction * rhsLabel = new LabelInstruction(func);
        if (!ir_land(cond, rhsLabel, endLabel)) {
            breakTargetLabels.pop_back();
            continueTargetLabels.pop_back();
            return false;
        }
        node->blockInsts.addInst(cond->blockInsts);
        node->blockInsts.addInst(rhsLabel);

        isShortCircuit = true;
    } else if (cond->node_type == ast_operator_type::AST_OP_LOR) {
        if (!ir_lor(cond, bodyLabel, endLabel)) {
            breakTargetLabels.pop_back();
            continueTargetLabels.pop_back();
            return false;
        }
        node->blockInsts.addInst(cond->blockInsts);
        node->blockInsts.addInst(bodyLabel);
        isShortCircuit = true;
    }

    if (!isShortCircuit) {
        ast_node * condNode = ir_visit_ast_node(cond);
        if (!condNode) {
            breakTargetLabels.pop_back();
            continueTargetLabels.pop_back();
            return false;
        }
        node->blockInsts.addInst(condNode->blockInsts);

        Value * condVal = condNode->val;
        if (condVal->getType()->isInt32Type()) {
            CastInstruction * castInst = new CastInstruction(func, condVal, IntegerType::getTypeBool());
            node->blockInsts.addInst(castInst);
            condVal = castInst;
        }

        node->blockInsts.addInst(new CondGotoInstruction(func, condVal, bodyLabel, endLabel));
    }

    // 5. 循环体部分
    if (!isShortCircuit) {
        // 只有非短路逻辑时才插入 bodyLabel
        node->blockInsts.addInst(bodyLabel);
    }
    ast_node * bodyNode = (node->sons.size() > 1 ? node->sons[1] : nullptr);
    if (bodyNode) {
        if (!ir_visit_ast_node(bodyNode)) {
            breakTargetLabels.pop_back();
            continueTargetLabels.pop_back();
            return false;
        }
        node->blockInsts.addInst(bodyNode->blockInsts);
    }

    // 6. 回跳条件判断
    node->blockInsts.addInst(new GotoInstruction(func, condLabel));

    // 7. 循环出口
    node->blockInsts.addInst(endLabel);

    // 8. 出栈
    breakTargetLabels.pop_back();
    continueTargetLabels.pop_back();

    node->val = nullptr;
    return true;
}

/// @brief break语句节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_break(ast_node * node)
{
    if (breakTargetLabels.empty()) {
        minic_log(LOG_ERROR, "第%lld行的break语句不在循环内", (long long) node->line_no);
        return false;
    }

    Function * func = module->getCurrentFunction();
    Instruction * targetLabel = breakTargetLabels.back(); // 获取最内层循环的出口标签

    node->blockInsts.addInst(new GotoInstruction(func, targetLabel));
    node->val = nullptr; // break语句没有值
    return true;
}

/// @brief continue语句节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_continue(ast_node * node)
{
    if (continueTargetLabels.empty()) {
        minic_log(LOG_ERROR, "第%lld行的continue语句不在循环内", (long long) node->line_no);
        return false;
    }

    Function * func = module->getCurrentFunction();
    Instruction * targetLabel = continueTargetLabels.back(); // 获取最内层循环的条件判断标签

    node->blockInsts.addInst(new GotoInstruction(func, targetLabel));
    node->val = nullptr; // continue语句没有值
    return true;
}

int IRGenerator::ir_constint_ast_node(ast_node * node)
{
    if (!node) {
        minic_log(LOG_ERROR, "空节点不能计算常量表达式");
        return 0;
    }

    switch (node->node_type) {
        case ast_operator_type::AST_OP_LEAF_LITERAL_UINT:
            return node->integer_val;

        case ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT:
            // 如果是浮点数，直接返回0，因为我们只处理整数常量表达式
            minic_log(LOG_ERROR, "不支持浮点数常量表达式计算（第%lld行）", (long long) node->line_no);
            return 0;

        case ast_operator_type::AST_OP_LEAF_VAR_ID: {
            Value * val = module->findVarValue(node->name);
            if (ConstInt * constInt = dynamic_cast<ConstInt *>(val)) {
                return constInt->getVal();
            } else if (ConstFloat * constFloat = dynamic_cast<ConstFloat *>(val)) {
                // 浮点常量转换为整数（截断）
                return (int) constFloat->getVal();
            } else {
                minic_log(LOG_ERROR, "常量表达式计算失败，第%lld行", (long long) node->line_no);
                return 0;
            }
        }
        case ast_operator_type::AST_OP_ADD:
            return IRGenerator::ir_constint_ast_node(node->sons[0]) + IRGenerator::ir_constint_ast_node(node->sons[1]);
        case ast_operator_type::AST_OP_SUB:
            return IRGenerator::ir_constint_ast_node(node->sons[0]) - IRGenerator::ir_constint_ast_node(node->sons[1]);

        case ast_operator_type::AST_OP_MUL:
            return IRGenerator::ir_constint_ast_node(node->sons[0]) * IRGenerator::ir_constint_ast_node(node->sons[1]);

        case ast_operator_type::AST_OP_DIV:
            return IRGenerator::ir_constint_ast_node(node->sons[0]) / IRGenerator::ir_constint_ast_node(node->sons[1]);

        default:
            minic_log(LOG_ERROR, "不支持的下标表达式操作类型（第%lld行）", (long long) node->line_no);
            return 0;
    }
}

float IRGenerator::ir_constfloat_ast_node(ast_node * node)
{
    if (!node) {
        minic_log(LOG_ERROR, "空节点不能计算浮点常量表达式");
        return 0.0f;
    }

    switch (node->node_type) {
        case ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT:
            return node->float_val;

        case ast_operator_type::AST_OP_LEAF_LITERAL_UINT:
            // 整数转浮点数
            return (float) node->integer_val;

        case ast_operator_type::AST_OP_LEAF_VAR_ID: {
            Value * val = module->findVarValue(node->name);
            if (ConstFloat * constFloat = dynamic_cast<ConstFloat *>(val)) {
                return constFloat->getVal();
            } else if (ConstInt * constInt = dynamic_cast<ConstInt *>(val)) {
                return (float) constInt->getVal();
            } else {
                minic_log(LOG_ERROR, "浮点常量表达式计算失败，第%lld行", (long long) node->line_no);
                return 0.0f;
            }
        }
        case ast_operator_type::AST_OP_ADD:
            return ir_constfloat_ast_node(node->sons[0]) + ir_constfloat_ast_node(node->sons[1]);
        case ast_operator_type::AST_OP_SUB:
            return ir_constfloat_ast_node(node->sons[0]) - ir_constfloat_ast_node(node->sons[1]);
        case ast_operator_type::AST_OP_MUL:
            return ir_constfloat_ast_node(node->sons[0]) * ir_constfloat_ast_node(node->sons[1]);
        case ast_operator_type::AST_OP_DIV:
            return ir_constfloat_ast_node(node->sons[0]) / ir_constfloat_ast_node(node->sons[1]);
        case ast_operator_type::AST_OP_UNARY_MINUS:
            return -ir_constfloat_ast_node(node->sons[0]);
        case ast_operator_type::AST_OP_UNARY_PLUS:
            return ir_constfloat_ast_node(node->sons[0]);

        default:
            minic_log(LOG_ERROR, "不支持的浮点常量表达式操作类型（第%lld行）", (long long) node->line_no);
            return 0.0f;
    }
}

bool IRGenerator::ir_array_decl(ast_node * node)
{
    // 前置条件检查
    if (!node || !node->parent || node->sons.size() < 2) {
        minic_log(LOG_ERROR, "Invalid array declaration node structure");
        return false;
    }

    // 安全获取祖父节点
    ast_node * graparent = node->parent->parent;
    Type * const_type = nullptr;
    if (graparent && graparent->node_type == ast_operator_type::AST_OP_CONST_DECL) {
        const_type = (graparent->sons.size() > 0 && graparent->sons[0]) ? graparent->sons[0]->type : nullptr;
    }

    // 初始化关键变量
    std::vector<int> dimensions;
    std::string arrayName;
    Type * pointerType = const_type;
    ast_node * init_node = nullptr;

    // 安全获取初始化节点
    auto & sons1 = node->sons[1]->sons;
    if (sons1.size() > 2 && sons1[2] && sons1[2]->node_type == ast_operator_type::AST_OP_ARRAY_INIT) {
        init_node = sons1[2];
    } else if (node->sons.size() > 2 && node->sons[2] && graparent &&
               graparent->node_type == ast_operator_type::AST_OP_CONST_DECL &&
               node->sons[2]->node_type == ast_operator_type::AST_OP_ARRAY_INIT) {
        init_node = node->sons[2];
    }

    // 使用迭代代替递归处理维度
    ast_node * current = node;
    while (current) {
        if (current->sons.size() < 2)
            break;

        ast_node * firstChild = current->sons[0];
        ast_node * secondChild = current->sons[1];

        if (!firstChild || !secondChild) {
            minic_log(LOG_ERROR, "Malformed array declaration at line %lld", (long long) node->line_no);
            return false;
        }

        switch (firstChild->node_type) {
            case ast_operator_type::AST_OP_LEAF_TYPE: {
                if (pointerType) {
                    minic_log(LOG_ERROR,
                              "Duplicate array type definition at line %lld",
                              (long long) firstChild->line_no);
                    return false;
                }
                pointerType = firstChild->type;
                current = secondChild;
                continue;
            }

            case ast_operator_type::AST_OP_LEAF_VAR_ID: {
                if (!arrayName.empty()) {
                    minic_log(LOG_ERROR, "Duplicate array name at line %lld", (long long) firstChild->line_no);
                    return false;
                }
                arrayName = firstChild->name;

                if (secondChild->node_type == ast_operator_type::AST_OP_CONST_EXP) {
                    if (secondChild->sons.empty() || !secondChild->sons[0]) {
                        minic_log(LOG_ERROR,
                                  "Invalid dimension expression at line %lld",
                                  (long long) secondChild->line_no);
                        return false;
                    }
                    dimensions.push_back(static_cast<int>(IRGenerator::ir_constint_ast_node(secondChild->sons[0])));
                }
                break;
            }

            case ast_operator_type::AST_OP_ARRAY_DECL: {
                if (secondChild->node_type == ast_operator_type::AST_OP_CONST_EXP) {
                    if (secondChild->sons.empty() || !secondChild->sons[0]) {
                        minic_log(LOG_ERROR,
                                  "Invalid dimension expression at line %lld",
                                  (long long) secondChild->line_no);
                        return false;
                    }
                    dimensions.push_back(static_cast<int>(IRGenerator::ir_constint_ast_node(secondChild->sons[0])));
                }
                current = firstChild;
                continue;
            }

            default:
                minic_log(LOG_ERROR, "Unexpected array declaration structure at line %lld", (long long) node->line_no);
                return false;
        }
        break;
    }

    // 后置条件验证
    if (!pointerType || arrayName.empty() || dimensions.empty()) {
        minic_log(LOG_ERROR, "Incomplete array declaration at line %lld", (long long) node->line_no);
        return false;
    }

    // 创建数组类型
    Type * fullPointerType = module->createPointerType(pointerType, dimensions);
    if (!fullPointerType) {
        minic_log(LOG_ERROR, "Failed to create array type at line %lld", (long long) node->line_no);
        return false;
    }

    // 变量创建
    Value * arrayVar = nullptr;
    if (Function * currentFunc = module->getCurrentFunction()) {
        arrayVar = module->newVarValue(fullPointerType, arrayName);
    } else {
        arrayVar = module->newGlobalVariable(fullPointerType, arrayName, nullptr);
    }

    if (!arrayVar) {
        minic_log(LOG_ERROR, "Failed to create array variable at line %lld", (long long) node->line_no);
        return false;
    }
    node->val = arrayVar;

    // 处理初始化
    if (init_node && init_node->sons.size() == 0 && !module->getCurrentFunction()) {
        return true;
    } else if (init_node && !ir_visit_ast_node(init_node)) {
        minic_log(LOG_ERROR, "Array initialization failed at line %lld", (long long) init_node->line_no);
        return false;
    }
    if (init_node) {
        node->blockInsts.addInst(init_node->blockInsts);
    }

    return true;
}

/// @brief 数组访问节点翻译成线性中间IR
/// @param node AST节点
/// @return
bool IRGenerator::ir_array_access(ast_node * node)
{
    if (!node || node->sons.size() != 2)
        return false;

    std::vector<Value *> access_dimensions;
    ast_node * base_var_node = nullptr;
    Value * arrayvar = nullptr;
    PointerType * pointerType = nullptr;

    // Step 1: 解析数组访问表达式，提取最底层数组变量名和所有维度表达式
    ast_node * cur = node;
    while (cur->node_type == ast_operator_type::AST_OP_ARRAY_ACCESS) {
        if (cur->sons.size() != 2) {
            minic_log(LOG_ERROR, "第%lld行的数组访问子节点数量错误", (long long) cur->line_no);
            return false;
        }

        ast_node * right = cur->sons[1];
        if (!ir_visit_ast_node(right)) {
            minic_log(LOG_ERROR, "第%lld行的数组访问右值表达式生成失败", (long long) right->line_no);
            return false;
        }

        node->blockInsts.addInst(right->blockInsts);

        if (!right->val) {
            minic_log(LOG_ERROR, "第%lld行的数组访问右值为空", (long long) right->line_no);
            return false;
        }
        access_dimensions.insert(access_dimensions.begin(), right->val);
        cur = cur->sons[0];
    }

    // Step 2: 确保底部变量是一个合法数组变量标识符
    if (!cur || cur->node_type != ast_operator_type::AST_OP_LEAF_VAR_ID) {
        minic_log(LOG_ERROR, "第%lld行数组访问基础变量非法", (long long) node->line_no);
        return false;
    }

    base_var_node = cur;
    arrayvar = module->findVarValue(base_var_node->name);
    if (!arrayvar) {
        minic_log(LOG_ERROR, "第%lld行变量%s未定义", (long long) node->line_no, base_var_node->name.c_str());
        return false;
    }

    pointerType = static_cast<PointerType *>(arrayvar->getType());

    // Step 3: 构造 GEP 指令
    std::vector<Value *> gep_indices;
    if (pointerType->isArray()) {
        gep_indices.push_back(module->newConstInt(0));
    }

    for (Value * idx: access_dimensions) {
        if (!idx) {
            minic_log(LOG_ERROR, "第%lld行数组下标中存在空值", (long long) node->line_no);
            return false;
        }
        gep_indices.push_back(idx);
    }
    int access_size = access_dimensions.size();
    Type * gepResultType = pointerType;
    if (access_size < pointerType->getDepth()) {
        while (access_size > 0) {
            gepResultType = const_cast<Type *>(static_cast<PointerType *>(gepResultType)->getElementType());
            access_size--;
        }
    } else {
        gepResultType = const_cast<Type *>(pointerType->getRootType());
    }

    auto gepInst =
        new GetElementPtrInstruction(module, module->getCurrentFunction(), arrayvar, gep_indices, gepResultType);
    node->blockInsts.addInst(gepInst);

    // **修复：通过分析索引数量来判断是否需要Load**
    // 计算总的维度数（不包括第一个0索引）
    int totalDimensions = pointerType->getDepth();
    int accessedDimensions = access_dimensions.size();

    if (accessedDimensions < totalDimensions) {
        // 没有完全索引到基本元素，说明结果仍然是数组，直接返回地址
        node->val = gepInst->getResult();
        return true;
    }

    // 完全索引到基本元素，生成Load指令
    Value * regvar = module->getCurrentFunction()->newTempVariable(gepResultType);
    auto loadInst = new LoadInstruction(module->getCurrentFunction(), regvar, gepInst->getResult());
    node->blockInsts.addInst(loadInst);
    node->val = regvar;

    return true;
}

bool IRGenerator::ir_array_init(ast_node * node)
{
    if (!node || node->node_type != ast_operator_type::AST_OP_ARRAY_INIT) {
        minic_log(LOG_ERROR, "Invalid array init node");
        return false;
    }
    // 获取数组声明节点
    ast_node * array_decl =
        node->parent->parent->node_type == ast_operator_type::AST_OP_CONST_DEF ? node->parent : node->parent->parent;
    if (!array_decl || array_decl->node_type != ast_operator_type::AST_OP_ARRAY_DECL || !array_decl->val) {
        minic_log(LOG_ERROR, "Array init without valid declaration");
        return false;
    }
    // 从已创建的Value中获取完整的数组类型
    Value * arrayVar = array_decl->val;
    Type * pointerType = arrayVar->getType();
    if (!pointerType->isPointerType()) {
        minic_log(LOG_ERROR, "Initializing non-array type");
        return false;
    }
    PointerType * arrType = static_cast<PointerType *>(pointerType);

    // 处理初始化列表
    std::vector<Value *> initValues;
    if (!process_init_list(node, arrType, initValues)) {
        return false;
    }

    // 创建全局或局部初始化
    if (module->getCurrentFunction()) {
        // 局部变量初始化
        ZeroSetInstruction * zeroSet =
            new ZeroSetInstruction(module->getCurrentFunction(), arrayVar, arrayVar->getType());
        node->blockInsts.addInst(zeroSet);
        return init_local_array(array_decl, arrType, initValues);
    } else {
        // 全局变量初始化
        return init_global_array(array_decl, arrType, initValues);
    }
}

bool IRGenerator::process_init_list(ast_node * initNode, PointerType * arrType, std::vector<Value *> & initValues)
{
    Type * elemType = const_cast<Type *>(arrType->getElementType());
    int totalElements = arrType->getSize() / arrType->getRootType()->getSize();

    for (int i = 0; i < initNode->sons.size(); i++) {
        ast_node * child = initNode->sons[i];

        if (initValues.size() >= totalElements) {
            minic_log(LOG_WARNING, "Initializer has too many elements, some will be ignored");
            break;
        }

        if (child->node_type == ast_operator_type::AST_OP_ARRAY_INIT) {
            // 嵌套初始化，必须进一步下降维度
            if (!elemType->isPointerType()) {
                minic_log(LOG_ERROR, "Nested initializer for non-array type");
                return false;
            }

            auto * subType = static_cast<PointerType *>(elemType);
            std::vector<Value *> subValues;

            if (!process_init_list(child, subType, subValues)) {
                return false;
            }

            // 注意：不能超过当前数组的元素总数
            int remain = totalElements - initValues.size();
            if (subValues.size() > remain) {
                subValues.resize(remain);
            }

            initValues.insert(initValues.end(), subValues.begin(), subValues.end());

        } else if (child->node_type == ast_operator_type::AST_OP_ARRAY_ACCESS) {
            if (!ir_array_access(child))
                return false;
            initValues.push_back(child->val);

        } else {
            // 处理可能带负号的表达式
            Value * val = process_expression_with_negation(child);
            if (!val) {
                minic_log(LOG_ERROR, "Invalid initializer value");
                return false;
            }
            initValues.push_back(val);
        }

        // 合并子语句产生的指令
        initNode->blockInsts.addInst(child->blockInsts);

        // 检查是否超过数组容量
        if (initValues.size() > totalElements) {
            minic_log(LOG_WARNING, "Initializer has too many elements, some will be ignored");
            break;
        }
    }

    // 自动补 0，类型与元素类型一致
    while ((int) initValues.size() < totalElements) {
        if (elemType->isFloatType()) {
            initValues.push_back(module->newConstFloat(0.0f));
        } else {
            initValues.push_back(module->newConstInt(0));
        }
    }

    return true;
}

bool IRGenerator::init_local_array(ast_node * array_decl,
                                   PointerType * arrType,
                                   const std::vector<Value *> & initValues)
{
    Function * func = module->getCurrentFunction();
    Value * arrayPtr = array_decl->val;
    int totalElements = arrType->getSize() / arrType->getRootType()->getSize();
    Type * expectedType = const_cast<Type *>(arrType->getRootType());
    ast_node * init_node = nullptr;
    if (array_decl->parent->node_type == ast_operator_type::AST_OP_CONST_DEF) {
        init_node = array_decl->sons[2];
    } else {
        init_node = array_decl->sons[1]->sons[2];
    }
    // 展开所有维度的初始化值
    std::vector<Value *> flattenedValues;
    if (!flatten_init_values(initValues, expectedType, totalElements, flattenedValues)) {
        return false;
    }
    // 生成store指令
    for (int i = 0; i < totalElements; ++i) {
        Value * initVal = i < flattenedValues.size() ? flattenedValues[i] : module->newConstInt(0);
        if (dynamic_cast<ConstInt *>(initVal)) {
            if (static_cast<ConstInt *>(initVal)->getVal() == 0) {
                continue; // 跳过零值
            }
        }
        std::vector<Value *> indices;
        calculate_array_indices(arrType, i, indices);
        GetElementPtrInstruction * gep = new GetElementPtrInstruction(module, func, arrayPtr, indices, expectedType);
        init_node->blockInsts.addInst(gep);

        // 直接 store 到 gep->getResult()，不要 load
        StoreInstruction * store = new StoreInstruction(func, gep->getResult(), initVal);
        init_node->blockInsts.addInst(store);
    }

    return true;
}

bool IRGenerator::flatten_init_values(const std::vector<Value *> & values,
                                      Type * expectedType,
                                      int maxElements,
                                      std::vector<Value *> & result)
{
    for (Value * val: values) {
        if (result.size() >= maxElements)
            break;

        if (ConstantArray * ca = dynamic_cast<ConstantArray *>(val)) {
            // 展开嵌套的ConstantArray
            std::vector<Value *> subValues;
            if (!flatten_init_values(ca->getValues(), expectedType, maxElements, subValues)) {
                return false;
            }
            result.insert(result.end(), subValues.begin(), subValues.end());
        } else {
            // 基本类型值
            if (!val->getType()->equals(expectedType)) {
                minic_log(LOG_ERROR, "Type mismatch in array initializer");
                return false;
            }
            result.push_back(val);
        }
    }
    return true;
}

void IRGenerator::calculate_array_indices(PointerType * arrType, int linearIndex, std::vector<Value *> & indices)
{
    indices.push_back(module->newConstInt(0)); // 数组指针偏移

    if (arrType->getElementType()->isPointerType()) {
        // 多维数组计算各维度索引
        PointerType * currentType = arrType;
        int remaining = linearIndex;

        while (currentType->getElementType()->isPointerType()) {
            Type * elemType = const_cast<Type *>(currentType->getElementType());
            PointerType * nextType = dynamic_cast<PointerType *>(elemType);
            if (!nextType) {
                minic_log(LOG_ERROR, "数组类型转换失败：不是有效的PointerType");
                break;
            }
            int subSize = nextType->getSize() / arrType->getRootType()->getSize();
            indices.push_back(module->newConstInt(remaining / subSize));
            remaining %= subSize;
            currentType = nextType;
        }
        indices.push_back(module->newConstInt(remaining));
    } else {
        // 一维数组直接使用线性索引
        indices.push_back(module->newConstInt(linearIndex));
    }
}

bool IRGenerator::init_global_array(ast_node * array_decl,
                                    PointerType * arrType,
                                    const std::vector<Value *> & initValues)
{
    // 对于全局变量，创建ConstantArray
    ConstantArray * constArray = module->newConstantArray(arrType, initValues);
    if (!constArray) {
        return false;
    }
    // 更新全局变量的初始化器
    GlobalVariable * globalVar = dynamic_cast<GlobalVariable *>(array_decl->val);
    if (globalVar) {
        globalVar->setInitializer(constArray);
    }

    return true;
}

/// @brief 宏定义声明节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_define_decl(ast_node * node)
{
    if (!node) {
        minic_log(LOG_ERROR, "宏定义声明节点为空");
        return false;
    }

    bool result = true;
    // 遍历所有的宏定义子节点
    for (auto & child: node->sons) {
        if (!child) {
            minic_log(LOG_ERROR, "宏定义声明的子节点为空");
            continue;
        }

        if (child->node_type != ast_operator_type::AST_OP_DEFINE_DEF) {
            minic_log(LOG_WARNING, "宏定义声明的子节点类型不是宏定义: %d", (int) child->node_type);
            continue;
        }

        result = ir_define(child);
        if (result) {
            node->blockInsts.addInst(child->blockInsts);
        } else {
            minic_log(LOG_ERROR, "处理宏定义节点失败");
            break;
        }
    }
    return result;
}

/// @brief define宏定义节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_define(ast_node * node)
{
    if (!node) {
        minic_log(LOG_ERROR, "宏定义节点为空");
        return false;
    }

    if (!module) {
        minic_log(LOG_ERROR, "模块指针为空");
        return false;
    }

    // #define 指令通常有两个子节点：宏名称和宏值
    if (node->sons.size() != 2) {
        minic_log(LOG_ERROR, "第%lld行的define指令子节点数量不正确: %zu", (long long) node->line_no, node->sons.size());
        return false;
    }

    ast_node * nameNode = node->sons[0];
    ast_node * valueNode = node->sons[1];

    if (!nameNode || !valueNode) {
        minic_log(LOG_ERROR, "第%lld行的define名称或值节点为空", (long long) node->line_no);
        return false;
    }

    // 处理宏名称
    if (nameNode->node_type != ast_operator_type::AST_OP_LEAF_VAR_ID) {
        minic_log(LOG_ERROR, "第%lld行的define名称不是有效标识符", (long long) nameNode->line_no);
        return false;
    }

    std::string macroName = nameNode->name;

    // 处理宏值
    Value * macroValue = nullptr;
    try {
        if (valueNode->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_UINT) {
            // 如果是整数字面量
            macroValue = module->newConstInt((int32_t) valueNode->integer_val);
        } else if (valueNode->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT) {
            // 如果是浮点数字面量
            macroValue = module->newConstFloat(valueNode->float_val);
        } else if (valueNode->node_type == ast_operator_type::AST_OP_LEAF_VAR_ID) {
            // 如果是其他标识符，尝试查找
            macroValue = module->findVarValue(valueNode->name);
            if (!macroValue) {
                minic_log(LOG_ERROR,
                          "第%lld行的define值引用了未定义的标识符: %s",
                          (long long) valueNode->line_no,
                          valueNode->name.c_str());
                return false;
            }
        } else {
            // 处理其他可能的值类型（如表达式）
            ast_node * processedValueNode = ir_visit_ast_node(valueNode);
            if (!processedValueNode || !processedValueNode->val) {
                minic_log(LOG_ERROR, "第%lld行的define值无法计算", (long long) valueNode->line_no);
                return false;
            }
            macroValue = processedValueNode->val;
        }
    } catch (...) {
        minic_log(LOG_ERROR, "处理宏值时发生异常");
        return false;
    }

    if (!macroValue) {
        minic_log(LOG_ERROR, "第%lld行的define值创建失败", (long long) valueNode->line_no);
        return false;
    }

    // 将宏添加到模块的常量表中
    try {
        module->addConstValue(macroName, macroValue);
    } catch (...) {
        minic_log(LOG_ERROR, "添加宏到常量表时发生异常");
        return false;
    }

    node->val = macroValue;
    return true;
}

/// @brief 类型转换表达式节点翻译成线性中间IR
/// @param node AST节点
/// @return 翻译是否成功，true：成功，false：失败
bool IRGenerator::ir_cast(ast_node * node)
{
    // 验证子节点数量 - 确保有目标类型和源表达式两个子节点
    if (node->sons.size() != 2) {
        minic_log(LOG_ERROR, "第%lld行的类型转换表达式子节点数量错误", (long long) node->line_no);
        return false;
    }

    // 处理目标类型节点 - 递归处理获取目标类型
    ast_node * targetTypeNode = ir_visit_ast_node(node->sons[0]);
    if (!targetTypeNode || !targetTypeNode->val) {
        minic_log(LOG_ERROR, "第%lld行的目标类型无效", (long long) node->line_no);
        return false;
    }
    Type * targetType = reinterpret_cast<Type *>(targetTypeNode->val);

    // 处理源表达式节点 - 递归处理获取源值
    ast_node * sourceExprNode = ir_visit_ast_node(node->sons[1]);
    if (!sourceExprNode || !sourceExprNode->val) {
        minic_log(LOG_ERROR, "第%lld行的源表达式无效", (long long) node->line_no);
        return false;
    }

    // 合并指令 - 将源表达式的IR指令添加到当前节点
    node->blockInsts.addInst(targetTypeNode->blockInsts);
    node->blockInsts.addInst(sourceExprNode->blockInsts);

    // 获取源值及其类型
    Value * sourceValue = sourceExprNode->val;
    Type * sourceType = sourceValue->getType();

    // === 关键修改：如果是 (void*) ← int，直接返回原值 ===
    if (targetType->isPointerType() && static_cast<PointerType *>(targetType)->getPointeeType()->isVoidType() &&
        sourceType->isInt32Type()) {
        node->val = sourceValue;
        return true;
    }

    // 类型检查 - 如果源类型和目标类型相同则跳过转换
    if (sourceType->equals(targetType)) {
        node->val = sourceValue;
        return true;
    }

    // 创建转换指令
    Function * currentFunc = module->getCurrentFunction();
    CastInstruction * castInst = new CastInstruction(currentFunc, sourceValue, targetType);
    node->blockInsts.addInst(castInst);

    // 返回结果 - 将转换指令作为节点的值返回
    node->val = castInst;
    return true;
}

// /// @brief 指针类型节点翻译成线性中间IR
// /// @param node AST节点
// /// @return 翻译是否成功，true：成功，false：失败
// bool IRGenerator::ir_pointer_type(ast_node * node)
// {
//     // 指针类型是叶节点，直接从node->type获取类型信息
//     if (!node->type) {
//         minic_log(LOG_ERROR, "第%lld行的指针类型节点未设置type信息", (long long) node->line_no);
//         return false;
//     }

//     // 直接使用节点已有的类型信息
//     node->val = reinterpret_cast<Value *>(node->type);
//     return true;
// }

/// @brief 将值转换为布尔类型（i1）
/// @param node 当前AST节点（用于错误定位）
/// @param val 要转换的值
/// @param code 生成的指令将添加到这个IR代码块中
/// @return 转换后的布尔值（i1类型）
Value * IRGenerator::convertToBool(ast_node * node, Value * val, InterCode & code)
{
    Function * func = module->getCurrentFunction();
    Type * type = val->getType();

    // 如果已经是i1，直接返回
    if (type->isInt1Byte()) {
        return val;
    }

    // 如果是整数（i32），则生成：icmp ne i32 val, 0
    if (type->isInt32Type()) {
        // 创建比较指令
        BinaryInstruction * cmpInst = new BinaryInstruction(func,
                                                            IRInstOperator::IRINST_OP_NEQ_I,
                                                            val,
                                                            module->newConstInt(0),
                                                            IntegerType::getTypeBool());
        code.addInst(cmpInst);
        return cmpInst;
    }

    // 如果是浮点数，则生成：fcmp one float val, 0.0
    if (type->isFloatType()) {
        // 创建浮点0.0常量
        Value * zeroFloat = module->newConstFloat(0.0f);
        // 创建比较指令
        BinaryInstruction * cmpInst =
            new BinaryInstruction(func, IRInstOperator::IRINST_OP_NEQ_I, val, zeroFloat, IntegerType::getTypeBool());
        code.addInst(cmpInst);
        return cmpInst;
    }

    // 其他类型不支持，报错
    minic_log(LOG_ERROR, "Unsupported type for boolean conversion at line %lld", (long long) node->line_no);
    return nullptr;
}

/// @brief 评估常量表达式，如果不是常量表达式则返回nullptr
/// @param node AST节点
/// @return 常量值，如果不是常量表达式则返回nullptr
Constant * IRGenerator::evalConstExpr1(ast_node * node)
{
    if (!node)
        return nullptr;

    // 对叶子节点直接处理
    if (node->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_UINT) {
        return module->newConstInt((int32_t) node->integer_val);
    }
    if (node->node_type == ast_operator_type::AST_OP_LEAF_LITERAL_FLOAT) {
        return module->newConstFloat(node->float_val);
    }
    if (node->node_type == ast_operator_type::AST_OP_LEAF_VAR_ID) {
        // 对于变量，检查是否为常量
        Value * val = module->findVarValue(node->name);
        if (Constant * constVal = dynamic_cast<Constant *>(val)) {
            // 必须是编译时常量，且不能是全局变量（因为全局变量可能被修改）
            if (dynamic_cast<GlobalVariable *>(val) == nullptr) {
                return constVal;
            }
        }
        return nullptr;
    }

    // 函数调用不是常量表达式
    if (node->node_type == ast_operator_type::AST_OP_FUNC_CALL) {
        return nullptr;
    }

    // 对二元运算符进行常量折叠
    if (node->sons.size() >= 2) {
        Constant * left = evalConstExpr1(node->sons[0]);
        Constant * right = evalConstExpr1(node->sons[1]);

        if (!left || !right)
            return nullptr; // 任一操作数不是常量，无法折叠

        // 根据操作类型进行计算
        switch (node->node_type) {
            case ast_operator_type::AST_OP_ADD:
                return foldConstantAdd(left, right);
            case ast_operator_type::AST_OP_SUB:
                return foldConstantSub(left, right);
            case ast_operator_type::AST_OP_MUL:
                return foldConstantMul(left, right);
            case ast_operator_type::AST_OP_DIV:
                return foldConstantDiv(left, right);
            case ast_operator_type::AST_OP_MOD:
                return foldConstantMod(left, right);
            default:
                break;
        }
    }

    // // 对一元运算符进行常量折叠（AST阶段已经实现）
    // if (node->sons.size() == 1) {
    //     Constant * operand = evalConstExpr1(node->sons[0]);
    //     if (!operand)
    //         return nullptr;

    //     switch (node->node_type) {
    //         case ast_operator_type::AST_OP_UNARY_MINUS:
    //             return foldConstantNeg(operand);
    //         case ast_operator_type::AST_OP_UNARY_PLUS:
    //             return operand;  // 一元加法不改变值
    //         default:
    //             break;
    //     }
    // }

    return nullptr; // 不是可折叠的常量表达式
}

/// @brief 折叠常量加法
Constant * IRGenerator::foldConstantAdd(Constant * left, Constant * right)
{
    if (ConstInt * leftInt = dynamic_cast<ConstInt *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 整数 + 整数
            return module->newConstInt(leftInt->getVal() + rightInt->getVal());
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 整数 + 浮点数 - 显式将整数转为浮点数
            return module->newConstFloat(static_cast<float>(leftInt->getVal()) + rightFloat->getVal());
        }
    }
    if (ConstFloat * leftFloat = dynamic_cast<ConstFloat *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 浮点数 + 整数 - 显式将整数转为浮点数
            return module->newConstFloat(leftFloat->getVal() + static_cast<float>(rightInt->getVal()));
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 浮点数 + 浮点数
            return module->newConstFloat(leftFloat->getVal() + rightFloat->getVal());
        }
    }
    return nullptr;
}

/// @brief 折叠常量减法
Constant * IRGenerator::foldConstantSub(Constant * left, Constant * right)
{
    if (ConstInt * leftInt = dynamic_cast<ConstInt *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 整数 - 整数
            return module->newConstInt(leftInt->getVal() - rightInt->getVal());
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 整数 - 浮点数 - 显式将整数转为浮点数
            return module->newConstFloat(static_cast<float>(leftInt->getVal()) - rightFloat->getVal());
        }
    }
    if (ConstFloat * leftFloat = dynamic_cast<ConstFloat *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 浮点数 - 整数 - 显式将整数转为浮点数
            return module->newConstFloat(leftFloat->getVal() - static_cast<float>(rightInt->getVal()));
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 浮点数 - 浮点数
            return module->newConstFloat(leftFloat->getVal() - rightFloat->getVal());
        }
    }
    return nullptr;
}

/// @brief 折叠常量乘法
Constant * IRGenerator::foldConstantMul(Constant * left, Constant * right)
{
    if (ConstInt * leftInt = dynamic_cast<ConstInt *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 整数 * 整数
            return module->newConstInt(leftInt->getVal() * rightInt->getVal());
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 整数 * 浮点数 - 显式将整数转为浮点数
            return module->newConstFloat(static_cast<float>(leftInt->getVal()) * rightFloat->getVal());
        }
    }
    if (ConstFloat * leftFloat = dynamic_cast<ConstFloat *>(left)) {
        if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
            // 浮点数 * 整数 - 显式将整数转为浮点数
            return module->newConstFloat(leftFloat->getVal() * static_cast<float>(rightInt->getVal()));
        }
        if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
            // 浮点数 * 浮点数
            return module->newConstFloat(leftFloat->getVal() * rightFloat->getVal());
        }
    }
    return nullptr;
}

/// @brief 折叠常量除法
Constant * IRGenerator::foldConstantDiv(Constant * left, Constant * right)
{
    // 检查除数是否为0
    if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
        if (rightInt->getVal() == 0) {
            minic_log(LOG_ERROR, "常量折叠时发现除以零错误");
            return nullptr;
        }
    }
    if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
        if (rightFloat->getVal() == 0.0f) {
            minic_log(LOG_ERROR, "常量折叠时发现除以零错误");
            return nullptr;
        }
    }
    // 如果有浮点数参与，直接跳过常量折叠，避免精度丢失
    if (dynamic_cast<ConstFloat *>(left) || dynamic_cast<ConstFloat *>(right)) {
        return nullptr;
    }

    // // 整数除法 - 优先转换为浮点数再除法
    // if (ConstInt * leftInt = dynamic_cast<ConstInt *>(left)) {
    //     if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
    //         // 检查是否需要浮点数除法(如果能整除则返回整数)
    //         if (leftInt->getVal() % rightInt->getVal() == 0) {
    //             return module->newConstInt(leftInt->getVal() / rightInt->getVal());
    //         } else {
    //             // 不能整除，返回浮点数结果保持精度
    //             return module->newConstFloat(static_cast<float>(leftInt->getVal()) /
    //                                          static_cast<float>(rightInt->getVal()));
    //         }
    //     }
    //     if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
    //         // 整数 / 浮点数 - 先将整数转为浮点数
    //         return module->newConstFloat(static_cast<float>(leftInt->getVal()) / rightFloat->getVal());
    //     }
    // }

    // // 浮点数除法
    // if (ConstFloat * leftFloat = dynamic_cast<ConstFloat *>(left)) {
    //     if (ConstInt * rightInt = dynamic_cast<ConstInt *>(right)) {
    //         // 浮点数 / 整数 - 先将整数转为浮点数
    //         return module->newConstFloat(leftFloat->getVal() / static_cast<float>(rightInt->getVal()));
    //     }
    //     if (ConstFloat * rightFloat = dynamic_cast<ConstFloat *>(right)) {
    //         // 浮点数 / 浮点数
    //         return module->newConstFloat(leftFloat->getVal() / rightFloat->getVal());
    //     }
    // }
    return nullptr;
}

/// @brief 折叠常量取模
Constant * IRGenerator::foldConstantMod(Constant * left, Constant * right)
{
    // 取模只支持整数操作数
    ConstInt * leftInt = dynamic_cast<ConstInt *>(left);
    ConstInt * rightInt = dynamic_cast<ConstInt *>(right);

    if (leftInt && rightInt) {
        // 检查除数是否为0
        if (rightInt->getVal() == 0) {
            minic_log(LOG_ERROR, "常量折叠时发现取模除以零错误");
            return nullptr;
        }
        return module->newConstInt(leftInt->getVal() % rightInt->getVal());
    }
    return nullptr;
}

/// @brief 折叠常量取负
Constant * IRGenerator::foldConstantNeg(Constant * operand)
{
    if (ConstInt * intVal = dynamic_cast<ConstInt *>(operand)) {
        return module->newConstInt(-intVal->getVal());
    }
    if (ConstFloat * floatVal = dynamic_cast<ConstFloat *>(operand)) {
        return module->newConstFloat(-floatVal->getVal());
    }
    return nullptr;
}